/**
 * 服务网点js
 */
$(function(){
	
	var map = new AMap.Map('mapContainer');
	//在地图中添加ToolBar插件
	map.plugin(["AMap.ToolBar"],function(){		
		toolBar = new AMap.ToolBar();
		map.addControl(toolBar);		
		toolBar.showDirection();//显示方向键盘
//		toolBar.showRuler();//显示标尺键盘
	});
	
	map.plugin('AMap.Geolocation', function () {
        geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,//是否使用高精度定位，默认:true
            timeout: 10000,          //超过10秒后停止定位，默认：无穷大
            maximumAge: 0,           //定位结果缓存0毫秒，默认：0
            convert: true,           //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
            showButton: true,        //显示定位按钮，默认：true
            buttonPosition: 'LB',    //定位按钮停靠位置，默认：'LB'，左下角
            buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
            showMarker: true,        //定位成功后在定位到的位置显示点标记，默认：true
            showCircle: false,        //定位成功后用圆圈表示定位精度范围，默认：true
            panToLocation: true,     //定位成功后将定位到的位置作为地图中心点，默认：true
            zoomToAccuracy:true      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
        });
        console.log("supported:"+geolocation.isSupported())
        if(!geolocation.isSupported()){
        	//加载城市查询插件
        	AMap.plugin(["AMap.CitySearch"], function() {
        		//实例化城市查询类
        		var citysearch = new AMap.CitySearch();
        		//自动获取用户IP，返回当前城市
        		citysearch.getLocalCity(function(status, result){
        			if(status === 'complete' && result.info === 'OK'){
        				if(result && result.city && result.bounds) {
        					var cityinfo = result.city;
        					var citybounds = result.bounds;
//        						document.getElementById('info').innerHTML = "您当前所在城市：" + cityinfo + "";
        					//地图显示当前城市
        					map.setBounds(citybounds);
        					currentPos = citybounds;
        					
        					var nearestMarketIndex = 0;
        					var marketResult = buildMarkers(map,currentPos.getCenter());
        					//上一次选择的服务网点
        					var premarker ;
//        					console.log(marketResult);
        					buildMarketsListener(marketResult.markets,map,premarker,marketResult.nearestMarketIndex,marketResult.nearestMarker);
        				}
        			}else{
        				console.log("无法获取IP和所在城市");
//        					document.getElementById('info').innerHTML = "您当前所在城市：" + result.info + "";
        			}
        		});
        	});
        }else{
        	map.addControl(geolocation);
        	AMap.event.addListener(geolocation, 'complete', function(data){
        		var lat = data.position.getLat();
        		var lng = data.position.getLng();
        		console.log("lat_lng:"+lat+"_"+lng);
        		var currentPos = new AMap.LngLat(lng,lat);
        		var marketResult = buildMarkers(map,currentPos)
        		//上一次选择的服务网点
        		var premarker ;
//        		console.log(marketResult);
        		buildMarketsListener(marketResult.markets,map,premarker,marketResult.nearestMarketIndex,marketResult.nearestMarker);
        	});//返回定位成功信息
        	AMap.event.addListener(geolocation, 'error', function(){
        		//解析定位错误信息
        		switch(data.info) {
        		case 'PERMISSION_DENIED':
        			console.log('浏览器阻止了定位操作');
        			break;
        		case 'POSITION_UNAVAILBLE':
        			console.log('无法获得当前位置');
        			break;
        		case 'TIMEOUT':
        			console.log('定位超时');
        			break;
        		default:
        			console.log('未知错误');
        		break;
        		}
        	});//返回定位出错信息
        	$(".amap-geo").click();
        }
    });
	
	/**
	 * 构造所有的服务网点
	 * @param nearestMarketIndex 离用户最近的服务网点索引
	 * @param map 地图对象
	 * @param currentPos 当前用户的位置
	 * 
	 */
	function buildMarkers(map,currentPos){
		var markets = [];
		//最近服务网点的索引
		var nearestMarketIndex = 0;
		//最近的距离
		var nearestMarker = 0;
		$.ajax({
			async:false,
			url:"/"+Udwin.appName+"/dealer/queryAll",
			method:"GET",
			success:function(data){
				//将每个服务网点添加标记
				if(data.result=="success"){
					var dealers = data.data;
					
					for (var i = 0; i < dealers.length; i++) {
						var imageIcon ;
						//实体店
						if(dealers[i].dealerType == '1'){
							imageIcon = "/"+Udwin.appName+"/images/mapico.png";
//							imageIcon = "http://webapi.amap.com/images/0.png";
						}else{
							imageIcon = "/"+Udwin.appName+"/images/mapico2.png";
						}
						//添加点标记，并使用自己的icon
						var marker = new AMap.Marker({	
							//复杂图标
							icon: new AMap.Icon({    
								//图标大小
								size:new AMap.Size(49,37),
								//大图地址
								image:imageIcon
							}),
							//在地图上添加点
							position:new AMap.LngLat(dealers[i].longitude,dealers[i].latitude),
							offset: new AMap.Pixel(-24,-37)
						});
						
						//如果获取到了当前城市
						if(currentPos){
							//取两点之间的距离最短的
//							var distance =Math.pow(dealers[i].longitude-currentPos.getLng(),2)+Math.pow(dealers[i].latitude-currentPos.getLat(),2);
							var distance =currentPos.distance(new AMap.LngLat(dealers[i].longitude,dealers[i].latitude));
//							console.log(distance);
							if(nearestMarker == 0){
								nearestMarker = distance;
								nearestMarketIndex = i;
							}else{
								if(nearestMarker > distance){
									nearestMarker = distance;
									nearestMarketIndex = i;
								}
							}
						}
						
						marker.dealerUuid = dealers[i].dealerUuid;
						marker.dealerType = dealers[i].dealerType;
						marker.setMap(map);  
						markets.push(marker);
					}
				}
			}
		})
		var result = {};
		result.markets = markets;
		result.nearestMarketIndex = nearestMarketIndex;
		result.nearestMarker = nearestMarker;
		return result;
	}
	
	/**
	 * 构造服务网点的监听事件和效果
	 * @param markets 服务网点数据
	 * @param map 地图
	 * @param premarker 上一次点击的服务网点
	 */
	function buildMarketsListener(markets,map,premarker,nearestMarketIndex,nearestMarker){
		
		for ( var i in markets) {
			//闭包处理，防止回调的时候，market是同一个对象
			(function(i){
				
				var market = markets[i];
				//鼠标点击marker弹出自定义的信息窗体
				AMap.event.addListener(market,'click',function(){ 
					map.clearInfoWindow();
					var innerContext="";
					
					if(premarker){
						var imageIcon ;
						//实体店
						if(premarker.dealerType == '1'){
							imageIcon = "/"+Udwin.appName+"/images/mapico.png";
						}else{
							imageIcon = "/"+Udwin.appName+"/images/mapico2.png";
						}
						premarker.setIcon(new AMap.Icon({    
							//图标大小
							size:new AMap.Size(49,37),
							//大图地址
							image:imageIcon
						}));
					}
					premarker = market;
//					console.log(premarker);
					market.setIcon("/"+Udwin.appName+"/images/mapico3.png");
					
					//
					$.ajax({
						async:false,
						url:"/"+Udwin.appName+"/dealer/detail/"+market.dealerUuid,
						method:'GET',
						success:function(data){
							if(data.result=="success"){
								var obj = data.data;
								$("body").data("seletedDealer",obj);
								innerContext = '<div style="heigth:300px;width: 246px;background-color:#fff;padding: 20px 20px 1px;position:relative">'+
								'<img id="closex" src="http://webapi.amap.com/images/close2.gif" style="position:absolute; right:10px;top:10px;">'+
								'<a id="dealerName" style="color:red;font-size:14px;">'+obj.dealerName+'</a>'+
								'<p style="border-top:dashed 1px #dcdcdc;padding-top: 10px;font-size:12px;">联系电话：'+obj.dealerTelephone+'</p><p style="font-size:12px">地址：'+obj.address+'</p>'+
								'</div>';
							}
						}
					})
					
					//实例化信息窗体
					var infoWindow = new AMap.InfoWindow({
						isCustom:true,  //使用自定义窗体
						content:innerContext,
						offset:new AMap.Pixel(13, -45)//-113, -140
					});
					
					infoWindow.open(map,market.getPosition());	
				});	
				
				if(parseInt(i)==nearestMarketIndex){
					//将最近的服务网点聚焦
					console.log("pre:"+map.getCenter());
					map.setCenter(market.getPosition())
					//如果距离的平方大于10
					if(nearestMarker>10000){
						map.setZoom(6);
					}else if(nearestMarker<=10000 && nearestMarker>5000){
						map.setZoom(8);
					}else if(nearestMarker<=5000 && nearestMarker>3000){
						map.setZoom(10);
					}else if(nearestMarker<=3000 && nearestMarker>1000){
						map.setZoom(12);
					}else if(nearestMarker<=1000){
						map.setZoom(13);
					}
					console.log("after:"+map.getCenter());
					AMap.event.trigger( market, "click");
					var a=setInterval(function(){
					   if($("body #dealerName").length>0){
							$("body #dealerName").trigger("click");
							clearInterval(a);
						}
					},200);
				}
			})(i);
			
			$("body").delegate("#closex","click",function(){
				map.clearInfoWindow();
			})
			
			$("body").delegate("#dealerName","click",function(){
				//获取网点信息
				var dealer=$("body").data("seletedDealer");
//				console.log(dealer);
				var imageList = dealer.imageList;
				var imageContext = "";
				for(var i=0;i<imageList.length;i++){
					if(i==0){
						imageContext+='	<img src="/'+Udwin.appName+imageList[i]+'"class="currentImage" style="width:345px;height:265px">';
					}else{
						imageContext+='	<img src="/'+Udwin.appName+imageList[i]+'"class="image" style="width:345px;height:265px;">';
					}
				}
				imageContext += '<div class="slider"><a href="javascript:void(0)" style="text-decoration:none;" class="slider-prev">&lt;</a><a href="javascript:void(0)" style="text-decoration:none;" class="slider-next">&gt;</a></div>';
				var content = 
					'<p style="color:red;font-size:18px;font-weight:900;text-align:center;">'+dealer.dealerName+'</p>'
					+'<div id="dealerImgs" style="position:relative;">'
					+imageContext
					+'</div>'
					+'<ul class="list-inline" style="padding-top:8px;">'
					+'	<li style="font-size:12px;padding:2px 5px;">等级：'+dealer.level+' </li>'
					+'	<li style="font-size:12px;padding:2px 5px;">累计业务量：'+dealer.businessVolume+' </li>'
					+'	<li style="font-size:12px;padding:2px 5px;">授权号：'+dealer.dealerNum+' </li>'
					+'	<li style="font-size:12px;padding:2px 5px;">营业时间：'+dealer.businessOurs+'  </li>'
					+'	<li style="font-size:12px;padding:2px 5px;">店主名称：'+dealer.dealerName+'  </li>'
					+'	<li style="font-size:12px;padding:2px 5px;">店主手机：'+dealer.dealerTelephone+'</li>'
					+'	<li style="font-size:12px;padding:2px 5px;">电话号码：'+dealer.dealerPhone+'</li>'
					+'	<li style="font-size:12px;padding:2px 5px;"> 地址：'+dealer.address+'</li>'
					+'</ul>';
				//href="http://float2006.tq.cn/static.jsp?version=vip&admiuin=9689351&ltype=0&iscallback=1&page_templete_id=91218&is_message_sms=0&is_send_mail=0&uin=9689351" target=_blank
				content+='<a style="background-color:#A30909;padding: 5px 20px 5px 20px;color: #fff;" class="online" >在线咨询';

				content+='<a style="background-color:#A30909;padding: 5px 20px 5px 20px;color: #fff;margin-left:70px" class="freeMeasure">免费预约量尺</a>';
				$("body #dealerDetail").html(content).show();
			})
		}
	}
	
	//定制量尺页面
	$("#workflow").delegate("#dzlc","click",function(){
		window.open("/"+Udwin.appName+"/resources/html/dzlc.html");
	})
	
	/**
	 * 网点多个图片切换
	 */
	$("body").delegate("#dealerImgs","mouseover",function(){
		$(".slider").show();
	})
	
	$("body").delegate("#dealerImgs","mouseout",function(){
		$(".slider").hide();
	})
	
	$("body").delegate(".slider-prev","click",function(){
		var currentImg = $("#dealerImgs .currentImage");
		if(currentImg.prev("img").length==0){
			return;
		}
		currentImg.removeClass("currentImage").addClass("image").prev("img").removeClass("image").addClass("currentImage");
	})
 
	$("body").delegate(".slider-next","click",function(){
		var currentImg = $("#dealerImgs .currentImage");
		if(currentImg.next("img").length==0){
			return;
		}
		currentImg.removeClass("currentImage").addClass("image").next("img").removeClass("image").addClass("currentImage");
	})
	
	/*$("body").delegate(".freeMeasure","click",function(){
		window.location.href="/udwin/resources/html/dzlchover.html";
	})*/
})